package com.example.lottery_system.controller;


import com.example.lottery_system.common.errcode.ControllerErrorCodeConstant;
import com.example.lottery_system.common.exception.ControllerException;
import com.example.lottery_system.common.utils.JacksonUtil;
import com.example.lottery_system.controller.param.DrawPrizeParam;
import com.example.lottery_system.controller.param.WinningRecordParam;
import com.example.lottery_system.controller.result.WinningRecordsResult;
import com.example.lottery_system.service.DrawPrizeService;
import com.example.lottery_system.service.Enum.ActivityPrizeTiersEnum;
import com.example.lottery_system.service.dto.WinningRecordsDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DrawPrizeController {

    @Autowired
    DrawPrizeService drawPrizeService;

    Logger logger = LoggerFactory.getLogger(DrawPrizeController.class);
    @RequestMapping("/draw-prize")
    public Boolean drawPrize(@RequestBody @Validated DrawPrizeParam param) {
        logger.info("drawPrize->DrawPrizeParam: " + JacksonUtil.writeValueAsString(param));

        // 加入到 RABBIT MQ队列进行异步处理
        drawPrizeService.drawPrize(param);

        return Boolean.TRUE;
    }

    @RequestMapping("/winning-records/show")
    public List<WinningRecordsResult> showWinningRecord(@Validated @RequestBody WinningRecordParam param) {
        logger.info("showWinningRecord::WinningRecordParam：{}", JacksonUtil.writeValueAsString(param));
       List<WinningRecordsDto> winningRecordsDtoList =  drawPrizeService.showWinningRecord(param);

        List<WinningRecordsResult> winningRecordsResultList = convertResult(winningRecordsDtoList);
        return winningRecordsResultList;
    }

    private List<WinningRecordsResult> convertResult(List<WinningRecordsDto> winningRecordsDtoList) {
        if (CollectionUtils.isEmpty(winningRecordsDtoList)) {
            throw new ControllerException(ControllerErrorCodeConstant.WINNING_RESULT_IS_EMPTY);
        }

        List<WinningRecordsResult> winningRecordsResultList = winningRecordsDtoList.stream().map(winningRecordsDto -> new WinningRecordsResult(
                winningRecordsDto.getWinnerId(),
                winningRecordsDto.getWinnerName(),
                winningRecordsDto.getPrizeName(),
                winningRecordsDto.getPrizeTier().getMsg(),
                winningRecordsDto.getWinningTime()
        )).collect(Collectors.toList());


        return winningRecordsResultList;
    }
}
